package oylj.recycle.all_in_one;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import com.e.csnprintersdk.BuildConfig;
import com.google.gson.Gson;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import oylj.recycle.all_in_one.camera.DeviceLib;
import oylj.recycle.all_in_one.camera.NetSDKLib;
import oylj.recycle.all_in_one.card.CardLib;
import oylj.recycle.all_in_one.face.FaceDetectorView;
import oylj.recycle.all_in_one.ic_card.IcCardLib;
import oylj.recycle.all_in_one.id_card.IdCardLib;
import oylj.recycle.all_in_one.pound.WeightLib;
import oylj.recycle.all_in_one.print.ImgPrintLib;
import oylj.recycle.all_in_one.qr_code.QrCodeLib;

import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import static oylj.recycle.all_in_one.Utils.compressImgToBase64;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private WebView webView;
    private QrCodeLib qrCodeLib;
    private IcCardLib icCardLib;
    private IdCardLib idCardLib;
    private WeightLib weightLib;
    private ImgPrintLib imgPrintLib;
    private FaceDetectorView faceDetectorView;
    private TextToSpeech mTts;
    private SurfaceView surfaceView1;
    private SurfaceView surfaceView2;
    private DeviceLib deviceLib1;
    private DeviceLib deviceLib2;
    private CardLib cardLib;


    private String recognitionType = "";
    private String recognitionValue = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       try {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);

           surfaceView1 = (SurfaceView) findViewById(R.id.surfaceView1);
           surfaceView1.getHolder().addCallback(new SurfaceHolder.Callback() {
               @Override
               public void surfaceCreated(@NonNull SurfaceHolder holder) {
//                        deviceLib1.startPlay();
               }

               @Override
               public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
               }

               @Override
               public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

               }
           });

           surfaceView2 = (SurfaceView) findViewById(R.id.surfaceView2);
           surfaceView2.getHolder().addCallback(new SurfaceHolder.Callback() {

               @Override
               public void surfaceCreated(@NonNull SurfaceHolder holder) {
//                        deviceLib2.startPlay();
               }

               @Override
               public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

               }

               @Override
               public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

               }
           });
           faceDetectorView = findViewById(R.id.face_detector_view);
           faceDetectorView.post(() -> faceDetectorView.setTranslationY(faceDetectorView.getHeight()));
           NetSDKLib.getInstance().init();
           initTts();
           checkAndRequestPermissions();
           // value 是 JavaScript 执行后的返回值
           Handler submitHandler = new Handler(Looper.getMainLooper()) {
               @Override
               public void handleMessage(@NonNull Message msg) {
                   Log.d(TAG, "handleMessage: " + msg.what + " " + msg.obj);
                   recognitionType = msg.what + "";
                   recognitionValue = (String) msg.obj;
                   webView.evaluateJavascript("javascript:recognizeFromAndroid()", new ValueCallback<String>() {
                       @Override
                       public void onReceiveValue(String value) {
                           // value 是 JavaScript 执行后的返回值
                       }
                   });
               }
           };
           faceDetectorView.setSubmitHandler(submitHandler);
           qrCodeLib = new QrCodeLib(MainActivity.this, submitHandler);
           idCardLib = new IdCardLib(MainActivity.this, submitHandler);
           icCardLib = new IcCardLib(MainActivity.this);
           imgPrintLib = new ImgPrintLib(MainActivity.this);
           cardLib = new CardLib(MainActivity.this);
           weightLib = new WeightLib();
           initWebview();

       }
       catch (Exception e){
           Log.e(TAG, "onCreate: ",e );
       }

    }
    private void initTts(){
        mTts = new TextToSpeech(this, status -> {
            if (status == TextToSpeech.SUCCESS) {
                // 设置TTS语言
                int result = mTts.setLanguage(Locale.CHINA);

                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    // 语言数据丢失或不支持
                    Log.e(TAG, "Language is not supported");
                }
            } else {
                Log.e(TAG, "Initialization failed with status: " + status);
            }
        });
    }

    @JavascriptInterface
    public void reloadPoundAndCamera(){
        Log.d(TAG, "reloadPoundAndCamera: ");
        try{
            if(weightLib != null){
                weightLib.destroy();
                weightLib = new WeightLib();
            }
            webView.post(()->{
                Log.d(TAG, "reloadPoundAndCamera: ");
                webView.removeJavascriptInterface("weightLib");
                webView.addJavascriptInterface(weightLib, "weightLib");
                webView.reload();
            });
        }catch (Exception e){
            Log.e(TAG, "reloadPoundAndCamera: "+e );
        }

    }
    private void  initWebview(){
        try {
            webView = findViewById(R.id.web_view);
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    return false;
                }
            });
            webView.setWebChromeClient(new WebChromeClient() {
                public boolean onConsoleMessage(ConsoleMessage cm) {
                    Log.d(TAG, "console" + cm.message());
                    return true;
                }

                @Override
                public void onPermissionRequest(final PermissionRequest request) {
                    runOnUiThread(() -> {
                        // 直接授予 WebView 页面所需的权限
                        request.grant(request.getResources());
                    });
                }
            });
            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setMediaPlaybackRequiresUserGesture(false);
            webSettings.setAllowFileAccess(true);
            webSettings.setAllowFileAccessFromFileURLs(true);
            webSettings.setAllowUniversalAccessFromFileURLs(true);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口，如window.open()，默认为false
            webSettings.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//是否使用缓存
            webSettings.setDomStorageEnabled(true);//DOM Storage
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            webView.addJavascriptInterface(this, "android");
            webView.addJavascriptInterface(icCardLib, "icCardLib");
            webView.addJavascriptInterface(imgPrintLib, "imgPrintLib");
            webView.addJavascriptInterface(weightLib, "weightLib");
            webView.addJavascriptInterface(cardLib, "cardLib");
            if (BuildConfig.DEBUG) {
                webView.loadUrl("https://mp.recsteel.cn/all_in_one/test/index.html");
            } else {
                webView.loadUrl("https://mp.recsteel.cn/all_in_one/index.html");
            }
        }catch (Exception e){
            Log.e(TAG, "initWebview: "+e );
        }
    }
    private void checkAndRequestPermissions() {
        // 要检查的权限列表
        String[] permissions = {
                android.Manifest.permission.RECORD_AUDIO,
                android.Manifest.permission.INTERNET,
                Manifest.permission.CAMERA,
        };

        List<String> permissionsNeeded = new ArrayList<>();

        // 检查每一个权限是否已被授予
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsNeeded.add(permission);
            }
        }
        Log.d(TAG, "checkAndRequestPermissions: "+permissionsNeeded);
        // 如果有需要的权限没有被授予，申请这些权限
        if (!permissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionsNeeded.toArray(new String[0]), 100);
        }
    }

    @JavascriptInterface
    public void  getSystemConfig( String json){
        try {
            SystemConfig systemConfig = new Gson().fromJson(json, SystemConfig.class);
            Log.d(TAG, String.format("getSystemConfig: json:%s ",json));
            weightLib.start(systemConfig.getPound());
            List<SystemConfig.Camera> cameras = systemConfig.getCameras();
            Log.d(TAG, "cameras: "+cameras);
            deviceLib1 = null;
            deviceLib2 = null;
            surfaceView1.post(() -> {
                surfaceView1.setVisibility(View.GONE);
                surfaceView1.setTranslationY(2000);
            });
            surfaceView2.post(() -> {
                surfaceView2.setVisibility(View.GONE);
                surfaceView2.setTranslationY(2000);
            });
            if(!cameras.isEmpty()){
                surfaceView1.post(() -> {
                    surfaceView1.setVisibility(View.VISIBLE);
                });
                deviceLib1 = new DeviceLib(MainActivity.this,surfaceView1,cameras.get(0));
                deviceLib1.startPlay();
            }
            if(cameras.size() > 1){
                surfaceView2.post(() -> {
                    surfaceView2.setVisibility(View.VISIBLE);
                });
                deviceLib2 = new DeviceLib(MainActivity.this,surfaceView2,cameras.get(1));
                deviceLib2.startPlay();
            }
            showSurfaceView();
            new Handler(Looper.getMainLooper()).postDelayed(this::checkDevice, 1000); // 1000 毫秒 = 1 秒
            Log.d(TAG, String.format("surfaceView1 %s %s surfaceView2 %s %s",surfaceView1.getTranslationY(),surfaceView1.getVisibility(),surfaceView2.getTranslationY(),surfaceView2.getVisibility()));

        }catch (Exception e){
            Log.e(TAG, "getSystemConfig: ",e );
        }
    }
    public void checkDevice(){
        if(!icCardLib.isInitialized()){
            mTts.speak("ic卡读卡器连接失败", TextToSpeech.QUEUE_FLUSH, null, null);
            return;
        }
        if(!idCardLib.isInitialized()){
            mTts.speak("身份证读卡器连接失败", TextToSpeech.QUEUE_FLUSH, null, null);
            return;
        }
        if(!weightLib.isInitialized()){
            mTts.speak("地磅连接失败", TextToSpeech.QUEUE_FLUSH, null, null);
            return;
        }
        if(!qrCodeLib.isInitialized()){
            mTts.speak("二维码扫描器连接失败", TextToSpeech.QUEUE_FLUSH, null, null);
            return;
        }
        if(!imgPrintLib.isInitialized()){
            mTts.speak("打印机连接失败", TextToSpeech.QUEUE_FLUSH, null, null);
            return;
        }
        mTts.speak("欢迎使用", TextToSpeech.QUEUE_FLUSH, null, null);
    }
    @JavascriptInterface
    public void  reStart( ){
        Intent restartIntent = getPackageManager()
                .getLaunchIntentForPackage(getPackageName());
        if (restartIntent != null) {
            restartIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(restartIntent);
            Process.killProcess(Process.myPid()); // 关闭当前进程
        }
    }


    @JavascriptInterface
    public String getCapture1() {
        if(deviceLib1 != null){
            return compressImgToBase64(deviceLib1.capture(),1);
        }else{
            return null;
        }
    }
    @JavascriptInterface
    public String getCapture2() {
        if(deviceLib2 != null){
            return compressImgToBase64(deviceLib2.capture(),1);
        }else{
            return null;
        }
    }
    @JavascriptInterface
    public String getRecognitionValue() {
        return recognitionValue;
    }

    @JavascriptInterface
    public String getRecognitionType() {
        return recognitionType;
    }

    @JavascriptInterface
    public void hideSurfaceView(){
        if(surfaceView1!=null&&deviceLib1!=null){
            surfaceView1.setTranslationY(2000);
        }
        if(surfaceView2!=null&&deviceLib2!=null){
            surfaceView2.setTranslationY(2000);
        }
    }

    @JavascriptInterface
    public void showSurfaceView(){
        if(surfaceView1!=null&&deviceLib1!=null){
            surfaceView1.setTranslationY(0);
        }
        if(surfaceView2!=null&&deviceLib2!=null){
            surfaceView2.setTranslationY(0);
        }
    }


    @JavascriptInterface
    public void showFaceDetectorView(){
        hideSurfaceView();
        faceDetectorView.animate()
                .translationY(0)  // 移动到屏幕顶部
                .setDuration(500) // 500ms 匀速动画
                .start();
        faceDetectorView.cameraFaceHelper.setCanDetector(true);
    }

    @JavascriptInterface
    public String getVersionName() throws PackageManager.NameNotFoundException {
        PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        return packageInfo.versionName;
    }
    @JavascriptInterface //仍然必不可少
    public void downloadApk(final String url) {
        Log.d(TAG, "downloadApk: "+url);
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);// TODO: Consider calling
        } else {
            //进度条
            final ProgressDialog pd;
            pd = new ProgressDialog(this);
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pd.setMessage("正在下载更新");
            pd.show();
            new Thread() {
                @Override
                public void run() {
                    try {
                        File file = null;
                        try {
                            file = getFileFromServer("\t\n" +
                                    url, pd);
                        } catch (Exception e) {
                            Log.d(TAG, "run: err" + e);
                        }
                        //安装APK
                        installApk(file);
                        pd.dismiss(); //结束掉进度条对话框
                    } catch (Exception e) {
                    }
                }
            }.start();
        }
    }

    public File getFileFromServer(String path, ProgressDialog pd) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis()+".apk");
            if (!file.exists()) {
                //先得到文件的上级目录，并创建上级目录，在创建文件
                file.getParentFile().mkdir();
                try {
                    //创建文件
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                //获取当前下载量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    protected void installApk(File file) {
        try {
            Log.d(TAG, "installApk: "+file.getAbsolutePath());
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.REQUEST_INSTALL_PACKAGES) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 100);
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    MainActivity.this
                    ,  MainActivity.this.getPackageName() + ".provider"
                    , file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

            startActivity(intent);
        } catch (Exception e) {
            Log.d(TAG, "installApk: " + e);
        }
    }
    @Override
    protected void onDestroy() {
        // while exiting the application, please make sure to invoke cleanup.
        /// 退出应用后，调用 cleanup 清理资源
        Log.d(TAG, "onDestroy: ");
        NetSDKLib.getInstance().cleanup();
        super.onDestroy();
    }
}
